# encoding: utf-8
import os
import datetime
import logging

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

from model.music import Musician, Recording, Photo

# /musician
class MusicianIndexHandler(webapp.RequestHandler):
    def get(self):
        musician_list = Musician.all().fetch(50)
        template_values = {
            'musician_list': musician_list,
        }
        path = os.path.join(os.path.dirname(__file__),
                            'template/musician_index.html')
        self.response.out.write(template.render(path, template_values))

# /musician/new
# Add a new musician.
class MusicianNewHandler(webapp.RequestHandler):
    def get(self):
        # A form for user to input the musician information.
        path = os.path.join(os.path.dirname(__file__),
                            'template/musician_new.html')
        self.response.out.write(template.render(path, {}))

    def post(self):
        # Save the musician then redirect to the detail page.
        m = Musician(name=self.request.get("name"),
                     biography = self.request.get("biography"),
                     birthdate = datetime.date.today())
        m.put()

        self.redirect('/musician/%d' % m.key().id())


# /musician/(.+)
# Show the detailed information of a musician.
class MusicianDetailHandler(webapp.RequestHandler):
    def get(self, key_name):
        musician = Musician.get_by_key_name(key_name)

        photos = musician.photos.fetch(10)

        values = { 'musician': musician,
            'photos': photos }
        path = os.path.join(os.path.dirname(__file__),
                            'template/musician_detail.html')
        self.response.out.write(template.render(path, values))


application = webapp.WSGIApplication(
    [('/musician', MusicianIndexHandler),
     ('/musician/new', MusicianNewHandler),
     ('/musician/(.+)', MusicianDetailHandler)],
    debug = True)


def main():
    run_wsgi_app(application)


if __name__ == "__main__":
    main()
